const request = require("../utils/request");
const {
  generateUniqueString,
  decryptCBC,
  encryptECB,
  decryptECB,
  getFormatError,
} = require("../utils");

const supabase = require("../utils/supabase");
const { useJwt } = require("../utils/jwt");

const LoginService = {
  // 登录
  login: async (data) => {
    try {
      let res = decryptCBC(
        decryptECB(data.data, data.key.toString().padEnd(32, "0")),
        generateUniqueString(data.key),
        decryptECB(data.iv, data.key.toString().padEnd(32, "0")),
      );
      const loginUser = JSON.parse(res);
      let findUser = await supabase
        .from("users")
        .select("*")
        .eq("account", loginUser.account);
      findUser = findUser?.data?.[0];

      if (findUser) {
        let findSecret = await supabase
          .from("secrets")
          .select("secret")
          .eq("uuid", findUser.uuid);
        findSecret = findSecret?.data?.[0]?.secret;
        const valid =
          encryptECB(loginUser.password, findSecret) === findUser.password_hash;
        if (valid) {
          // 密码正确
          return useJwt.sign(data);
        } else {
          const err = new Error("账号或密码错误");
          err.status = 400;
          throw err;
        }
      } else {
        const err = new Error("账号或密码错误");
        err.status = 400;
        throw err;
      }
    } catch (err) {
      throw getFormatError(err, {
        status: 500,
      });
    }
  },
  // 退出登录
  logout: async (data) => {
    try {
    } catch (err) {
      throw getFormatError(err, {
        status: 500,
      });
    }
  },
};

module.exports = LoginService;
